from django_redis import get_redis_connection
from rest_framework import serializers
from users.models import User
from oauth.models import OAuthQQUser


class QQTokenSerializer(serializers.Serializer):

    # 创建qq关联数据和用户模型数据
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号',regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码',max_length=20,min_length=8)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6)

    def validate(self, attrs):

        # 验证access_token
        access_token = attrs['access_token']
        openid = OAuthQQUser.check_save_user_token(access_token)

        # 判断opendi
        if openid is None:
            raise serializers.ValidationError('无效的token')

        # 添加token，保存数据使用
        attrs['openid'] = openid

        # 验证短信码
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)

        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        # 判断手机号是否被注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            # 说明没有异常，用户已经注册过美多
            # 判断用户的密码
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')

            # 将用户数据保存
            attrs['user'] = user
            # print(attrs)

        return attrs



    def create(self, validated_data):

        # 判断数据库中是否有user
        # openid = validated_data.get('openid')
        user = validated_data.get('user')

        # print(openid)
        # iduser = OAuthQQUser.objects.get(openid=validated_data.get('openid')).user_id
        # print(iduser)
        # user = OAuthQQUser.objects.get(openid=openid).user
        # 如果没有则创建一个用户
        if not user:
            user = User.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )
            # 将密码进行加密处理
            user.set_password(validated_data['password'])
            user.save()

        # 保存第三方（qq）授权的数据
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )

        # 返回user
        return user

# OrderedDict([('access_token', 'eyJhbGciOiJIUzI1NiIsImV4cCI6MTUzMzMwMjAwNywiaWF0IjoxNTMzMjk4NDA3fQ.eyJvcGVuaWQiOiIwMkFDMDYyOEVCQjA3RkY3QzY5QjY3OTJFREMyQzg1NSJ9.qLkqmevSZHarNd-caDWmRDJ95i2KhqNYVCsonS63lec'), ('mobile', '13766211605'), ('password', '22222222'), ('sms_code', '358055'), ('openid', '02AC0628EBB07FF7C69B6792EDC2C855'), ('user', <User: xiaoting>)])
